import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/pages/goods/controller/comment_ctr.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../../utils/permission_utiil.dart';

//商品评价页面
class CommentPage extends GetView<CommentController> {
  const CommentPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CommentController>(builder: (controller) {
      return BasePage(
        title: "发表评论",
        iconType: IconType.back,
        children: [
          //顶部
          Container(
            color: Colors.white,
            child: Column(
              children: [
                Container(
                  decoration: bottom_gary_border,
                  margin: EdgeInsets.fromLTRB(18.w, 26.w, 18.w, 0.w),
                  padding: EdgeInsets.only(bottom: 10.w),
                  child: Row(
                    children: [
                      Text("商品评价", style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#333333"))),
                      SizedBox(
                        width: 10.w,
                      ),
                      starBox('main', controller.mainStar),
                      SizedBox(
                        width: 20.w,
                      ),
                      Text(controller.commentTxt, style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#333333")))
                    ],
                  ),
                ),
                //文本盒子
                Container(
                    margin: EdgeInsets.fromLTRB(18.w, 10.w, 18.w, 0.w),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Icon(Icons.border_color_outlined, size: 20, color: Tools.fromHex("#666666")),
                        SizedBox(
                          width: 5.w,
                        ),
                        Container(
                          width: 300.w,
                          height: 100.h,
                          child: TextFormField(
                            decoration: descript("感觉怎么样，跟大家分享一下吧～"),
                            controller: controller.contentController,
                            maxLines: 5,
                            onChanged: (value) {
                              controller.count = controller.contentController.text.length;
                              controller.update();
                            },
                          ),
                        ),
                      ],
                    )),

                Container(
                  padding: EdgeInsets.only(left: 18.w),
                  child: Row(
                    children: [
                      Text("已写", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#999999"))),
                      Text("${controller.count}", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#F83F2D"))),
                      Text("个字", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#999999"))),
                    ],
                  ),
                ),

                //拍照区

                controller.imageList!.isEmpty
                    ? PictureBox(
                        height: 115.h,
                      )
                    : Container(
                        padding: EdgeInsets.all(18.w),
                        alignment: Alignment.topLeft,
                        child: Wrap(spacing: 10.w, runSpacing: 10.w, direction: Axis.horizontal, children: [
                          for (var item in controller.imageList!) ImageItem(item: item),
                          controller.imageList!.length < 9
                              ? PictureBox(
                                  width: 100.w,
                                  height: 100.w,
                                  margin: EdgeInsets.zero,
                                )
                              : const SizedBox()
                        ]

                            // List.generate(controller.imageList!.length, (index){
                            //   return ImageItem(index: index);
                            // }),
                            ),
                      ),
                Container(
                  width: double.infinity,
                  margin: EdgeInsets.only(left: 18.w, bottom: 10.w),
                  child: Text("您的评价内容在商品评价页面将会被匿名展示。", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#999999"))),
                )
              ],
            ),
          ),

          //物流服务评价
          Container(
            margin: EdgeInsets.only(top: 10.w),
            padding: EdgeInsets.fromLTRB(18.w, 10.w, 18.w, 24.w),
            decoration: border_radis(Colors.white),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [Text("物流服务评价", style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#8F4B0A"))), Text("满意请给五星哦", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#8F4B0A")))],
                ),
                SizedBox(
                  height: 12.h,
                ),
                Container(
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [Text("商品符合度"), starBox('spfhd', controller.spfhdStar), SizedBox(width: 20.w)],
                  ),
                ),
                SizedBox(
                  height: 12.h,
                ),
                Container(
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [Text("店家服务..."), starBox('djfw', controller.djfwStar), SizedBox(width: 20.w)],
                  ),
                ),
                SizedBox(
                  height: 12.h,
                ),
                Container(
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [Text("快递配送..."), starBox('kdps', controller.kdpsStar), SizedBox(width: 20.w)],
                  ),
                ),
                SizedBox(
                  height: 12.h,
                ),
                Container(
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [Text("快递员服务"), starBox('kdyfw', controller.kdyfwStar), SizedBox(width: 20.w)],
                  ),
                ),
                SizedBox(
                  height: 12.h,
                ),
                Container(
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [Text("快递包装..."), starBox('kdbz', controller.kdbzStar), SizedBox(width: 20.w)],
                  ),
                ),
                SizedBox(
                  height: 120.h,
                ),
              ],
            ),
          ),

          Positioned(
              key: GlobalKey(debugLabel: 'Positioned'),
              bottom: 0,
              child: Container(
                padding: EdgeInsets.fromLTRB(18.w, 10.w, 18.w, 10.w),
                width: 375.w,
                height: 60.h,
                color: Colors.white,
                child: solidButton("提交", () {
                  controller.submit();
                }),
              ))
        ],
      );
    });
  }

  ///星星组件
  Widget starBox(String type, double value) {
    return RatingBar.builder(
      itemSize: 20,
      initialRating: value,
      minRating: 1,
      direction: Axis.horizontal,
      allowHalfRating: false,
      itemCount: 5,
      itemPadding: EdgeInsets.symmetric(horizontal: 2.0.w),
      itemBuilder: (context, _) => Icon(
        Icons.star,
        color: Tools.fromHex("#F93B19"),
      ),
      onRatingUpdate: (rating) {
        switch (type) {
          case 'main':
            controller.mainStar = rating;
            switch (rating) {
              case 1:
                controller.commentTxt = '很差';
                break;
              case 2:
                controller.commentTxt = '差';
                break;
              case 3:
                controller.commentTxt = '一般';
                break;
              case 4:
                controller.commentTxt = '好';
                break;
              case 5:
                controller.commentTxt = '非常好';
                break;
              default:
            }
            controller.update();
            break;
          case 'spfhd':
            controller.spfhdStar = rating;
            break;
          case 'djfw':
            controller.djfwStar = rating;
            break;
          case 'kdps':
            controller.kdbzStar = rating;
            break;
          case 'kdyfw':
            controller.kdyfwStar = rating;
            break;
          case 'kdbz':
            controller.kdbzStar = rating;
            break;
          default:
        }
      },
    );
  }
}

class PictureBox extends StatelessWidget {
  final CommentController controller = Get.find<CommentController>();

  final double? width;
  final double? height;
  final EdgeInsets? margin;
  PictureBox({
    super.key,
    this.width,
    this.height = 115,
    this.margin,
  });

  @override
  Widget build(BuildContext context) {
    return BaseInteractive(
      onClick: () {
        showModalBottomSheet(
          backgroundColor: Colors.transparent,
          context: context,
          builder: (BuildContext context) {
            return Container(
              padding: EdgeInsets.only(left: 8.w, right: 8.w),
              height: 180.h,
              child: Column(
                children: <Widget>[
                  BaseInteractive(
                      onClick: () async {
                        //拍照
                        PermissionUtil.checkPermission(Permission.camera).then((v) async {
                          if (v) {
                            final AssetEntity? entity = await CameraPicker.pickFromCamera(context);
                            controller.imageList!.add(entity!);
                            controller.update();
                            Get.back();
                          }
                        });
                      },
                      childWidget: Container(
                          decoration: const BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(20.0),
                                topRight: Radius.circular(20.0),
                              )),
                          alignment: Alignment.center,
                          width: double.infinity,
                          height: 50.h,
                          child: Text("拍照", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Tools.fromHex("#4D87FF"))))),
                  BaseInteractive(
                      onClick: () async {
                        if (controller.imageList.isEmpty) {
                          PermissionUtil.checkPermission(Permission.photos).then((v) async {
                            if (v) {
                              controller.imageList = await AssetPicker.pickAssets(context) ?? [];
                            }
                          });
                        } else {
                          controller.imageList.addAll((await AssetPicker.pickAssets(context, pickerConfig: AssetPickerConfig(maxAssets: 9 - controller.imageList!.length))) as Iterable<AssetEntity>);
                        }
                        controller.update();
                        Get.back();
                      },
                      childWidget: Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: const BorderRadius.only(
                              bottomLeft: Radius.circular(20.0),
                              bottomRight: Radius.circular(20.0),
                            ),
                            border: Border(
                              top: BorderSide(
                                color: Tools.fromHex("#D7D7D7"),
                                width: 1.0,
                              ),
                            ),
                          ),
                          alignment: Alignment.center,
                          width: double.infinity,
                          height: 50.h,
                          child: Text("从相册选择", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Tools.fromHex("#4D87FF"))))),
                  BaseInteractive(onClick: () => {Get.back()}, childWidget: Container(decoration: border_radis(Colors.white, radiusValue: 20), margin: EdgeInsets.only(top: 10.w), alignment: Alignment.center, width: double.infinity, height: 50.h, child: Text("取消", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Tools.fromHex("#4D87FF"))))),
                ],
              ),
            );
          },
        );
      },

      // () async {
      //   if(controller.imageList!.isEmpty){
      //     controller.imageList = await AssetPicker.pickAssets(context);
      //   }else{
      //     controller.imageList!.addAll((await AssetPicker.pickAssets(context,pickerConfig: AssetPickerConfig(
      //       maxAssets: 9-controller.imageList!.length
      //     ))) as Iterable<AssetEntity>);
      //   }
      //   controller.update();

      // },
      childWidget: Container(
        width: width ?? double.infinity,
        margin: margin ?? EdgeInsets.fromLTRB(18.w, 10.w, 18.w, 10.w),
        height: height,
        decoration: border_radis(Tools.fromHex("#F7F7F7")),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [BaseImage(url: "comment_camera.png", width: 44, height: 44), const Text("添加视频/图")],
        ),
      ),
    );
  }
}

class ImageItem extends StatelessWidget {
  final AssetEntity item;

  final CommentController controller = Get.find<CommentController>();
  ImageItem({
    super.key,
    required this.item,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      width: 100.w,
      height: 100.w,
      child: Stack(
        children: [
          Positioned(
              key: GlobalKey(debugLabel: 'Positioned'),
              child: Container(
                color: Colors.grey,
                width: 95.w,
                height: 95.w,
                child: AssetEntityImage(item, width: 95.w, height: 95.w, isOriginal: true),
              )),
          Positioned(
              key: GlobalKey(debugLabel: 'Positioned'),
              top: 0,
              right: 0,
              child: BaseInteractive(
                onClick: () {
                  controller.imageList.removeAt(controller.imageList.indexOf(item));
                  controller.update();
                },
                childWidget: const Icon(Icons.close, color: Colors.white, size: 16),
              ))
        ],
      ),
    );
  }
}
